package com.jourwon.spring.boot.advice;

import com.jourwon.spring.boot.model.vo.CommonResponseVO;
import com.jourwon.spring.boot.util.ObjectMapperUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;

/**
 * 统一响应处理
 *
 * @author JourWon
 * @date 2022/6/26
 */
@RestControllerAdvice
public class CommonResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 过滤swagger接口文档对应的返回类型returnType
     */
    private static final String[] EXCLUDE = {"Swagger2Controller", "Swagger2ControllerWebMvc", "ApiResourceController"};

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 避免swagger失效
        if (Arrays.asList(EXCLUDE).contains(returnType.getDeclaringClass().getSimpleName())) {
            return false;
        }
        if (returnType.getDeclaringClass().isAnnotationPresent(ApiIgnore.class)) {
            return false;
        }

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof CommonResponseVO) {
            return body;
        } else if (body == null) {
            return CommonResponseVO.success();
        } else if (body instanceof String) {
            CommonResponseVO<String> commonResponse = CommonResponseVO.success((String) body);
            return ObjectMapperUtils.objToJson(commonResponse);
        } else {
            return CommonResponseVO.success(body);
        }
    }

}
